package com.xbongbong.workflow.service.strategy.data.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.help.PaasFormDataHelper;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.message.pojo.dto.ConsistencySyncRabbitMqDTO;
import com.xbongbong.pro.suppliercommunicate.pojo.dto.SupplierDynamicAddDTO;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.SupplierProductEntity;
import com.xbongbong.saas.domain.entity.SupplierUserEntity;
import com.xbongbong.saas.domain.entity.ext.SupplierEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.help.workflow.SupplierHelp;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.model.SupplierProductModel;
import com.xbongbong.saas.model.SupplierUserModel;
import com.xbongbong.saas.service.ConsistencySyncService;
import com.xbongbong.saas.service.SupplierCommunicateService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.User;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 *
 * @author 魏荣杰
 *
 */
@Service
@Slf4j
public class WorkflowSupplierStrategy extends AbstractWorkflowDataStrategy implements WorkflowDataProcessStrategy {

    @Resource
    private UserModel userModel;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private SupplierCommunicateService supplierCommunicateService;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private SupplierUserModel supplierUserModel;
    @Resource
    private SupplierProductModel supplierProductModel;
    @Resource
    private SupplierHelp supplierHelp;
    @Resource
    private ConsistencySyncService consistencySyncService;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private PaasFormDataHelper paasFormDataHelper;

    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.SUPPLIER.getCode());
    }

    @Override
    public void save(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        String corpid = workflowTransferPOJO.getCorpid();
        User user = workflowTransferPOJO.getUser();
        Data pojoData = workflowTransferPOJO.getData();
        Long dataId = pojoData.getId();
        JSONObject data = pojoData.getData();

        // 产品保存
        JSONArray productIdArray = data.getJSONArray(SupplierEnum.PRODUCT_LIST.getAttr());
        String supplierName = data.getString(SupplierEnum.SUPPLIER_NAME.getAttr());
        if (BasicConstant.ONE.equals(workflowTransferPOJO.getIsImport()) || (Objects.nonNull(productIdArray) && !productIdArray.isEmpty())) {
            //新建或编辑可见产品字段
            supplierHelp.saveSupplierProduct(true, corpid, dataId, supplierName, productIdArray);
        }

        // 供应商联系人保存
        List<ValidateDataDTO> validateDataDTOList = new ArrayList<>();
        if (saasNeedRedundantAttrPojo != null) {
            validateDataDTOList = saasNeedRedundantAttrPojo.getNeedAddValidateDataDTO();
            for (ValidateDataDTO validateDataDTO : validateDataDTOList) {
                validateDataDTO.setProcessCreatorId(user.getUserId());
            }
        }
        if (CollectionsUtil.isNotEmpty(validateDataDTOList)) {
            UserEntity userEntity = userModel.getByKeyIngoreDel(user.getUserId(), corpid);
            UserVO userVO = new UserVO();
            BeanUtil.copyProperties(userEntity, userVO);
            paasFormDataHelper.batchEditContact(saasNeedRedundantAttrPojo, userVO, user.getUserId(), corpid, dataId, data.getString(SupplierEnum.SUPPLIER_NAME.getAttr()), workflowTransferPOJO.getIsImport(), SupplierContactEnum.SUPPLIER_ID.getAttr(), XbbRefTypeEnum.SUPPLIER_CONTACT);
//            paasFormDataService.batchAddContact(validateDataDTOList, dataId, formDataAddDTO.getLoginUser(), SupplierContactEnum.SUPPLIER_ID.getAttr(), XbbRefTypeEnum.SUPPLIER_CONTACT);
        }


        //项目日志记录(供应商新建的动态数据从这里拿的)
        try {
            String supplieName = "";
            String communicateMemo = "";
            supplieName = data.getString(SupplierEnum.SUPPLIER_NAME.getAttr());
            String operate = Objects.equals(workflowTransferPOJO.getIsImport(), 1) ? I18nMessageUtil.getMessage(I18nStringConstant.IMPORTED) : I18nMessageUtil.getMessage(I18nStringConstant.ADD);
            communicateMemo = user.getName() + operate + I18nMessageUtil.getMessage(CommonConstant.SUPPLIER) + " :" + supplieName;
            SupplierDynamicAddDTO supplierDynamicAddDTO = new SupplierDynamicAddDTO();
            supplierDynamicAddDTO.setCorpid(corpid);
            supplierDynamicAddDTO.setUserId(user.getUserId());
            supplierDynamicAddDTO.setSupplierId(dataId);
            supplierDynamicAddDTO.setSupplierName(supplierName);
            supplierDynamicAddDTO.setMemo(communicateMemo);
            supplierDynamicAddDTO.setCommunicateBusinessText(supplieName);//CommunicateBusinessText 是在动态展示时用的，合同是流水号，人一般是名称，eg：供应商：周杰伦
            supplierDynamicAddDTO.setCommunicateBusinessType(XbbRefTypeEnum.SUPPLIER.getCode());
            supplierDynamicAddDTO.setDataId(dataId);//动态数据获取就是 依赖 dataId 和 businessType
            supplierDynamicAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
            supplierCommunicateService.addSupplierDynamic(supplierDynamicAddDTO);
        }catch (Exception e){
            log.error("供应商新增项目日志记录失败",e);
        }

        // api
        apiHook(workflowTransferPOJO);
        addLinkDataDynamic(workflowTransferPOJO);
        // log
        afterSaveLog(workflowTransferPOJO);
    }

    @Override
    public void update(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);


        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        JSONObject data = pojoData.getData();
        Long dataId = pojoData.getId();
        User user = workflowTransferPOJO.getUser();


        // 产品保存
        JSONArray productIdArray = data.getJSONArray(SupplierEnum.PRODUCT_LIST.getAttr());
        String supplierName = data.getString(SupplierEnum.SUPPLIER_NAME.getAttr());
        if (BasicConstant.ONE.equals(workflowTransferPOJO.getIsImport()) || (Objects.nonNull(productIdArray) && !productIdArray.isEmpty())) {
            //新建或编辑可见产品字段
            supplierHelp.saveSupplierProduct(true, corpid, dataId, supplierName, productIdArray);
        }

        UserEntity userEntity = userModel.getByKeyIngoreDel(user.getUserId(), corpid);
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(userEntity, userVO);
        paasFormDataHelper.batchEditContactForUpdate(saasNeedRedundantAttrPojo, userVO, user.getUserId(), corpid, dataId, data.getString(SupplierEnum.SUPPLIER_NAME.getAttr()), workflowTransferPOJO.getIsImport(), SupplierContactEnum.SUPPLIER_ID.getAttr(), XbbRefTypeEnum.SUPPLIER_CONTACT);
//                paasFormDataService.batchEditContact(corpid, needAddValidateDataDTO, needUpdateValidateDataDTO, needDelValidateDataDTO, dataId, userVO, SupplierContactEnum.SUPPLIER_ID.getAttr(),XbbRefTypeEnum.SUPPLIER_CONTACT);


        // 数据一致性同步
        try{
            WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(workflowTransferPOJO.getBackupDataId(), corpid);
            String oldSupplierName = FastJsonHelper.getStringOrDefaultFromFormData(workflowBackupDataEntity.getData(), SupplierEnum.SUPPLIER_NAME.getAttr(), "");
            String opObjectName = data.getString(SupplierEnum.SUPPLIER_NAME.getAttr());
            if (!Objects.equals(oldSupplierName, opObjectName)) {
                ConsistencySyncRabbitMqDTO consistencySyncRabbitMqDTO = new ConsistencySyncRabbitMqDTO(corpid, dataId, opObjectName);
                consistencySyncService.syncSupplier(consistencySyncRabbitMqDTO);
            }
        }catch (Exception e){
            log.error("数据一致性同步", e);
        }

        // api
        apiHook(workflowTransferPOJO);
        // log
        afterUpdateLog(workflowTransferPOJO);
    }

    @Override
    public void updateBack(Long taskId, WorkflowTransferPOJO workflowTransferPOJO) throws XbbException {
        String corpid = workflowTransferPOJO.getCorpid();
        Long backupDataId = workflowTransferPOJO.getBackupDataId();
        Long dataId = workflowTransferPOJO.getData().getId();
        WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(backupDataId, corpid);
        if (Objects.nonNull(workflowBackupDataEntity)) {
            JSONObject data = workflowBackupDataEntity.getData();

            replenishAttrForBackupData(workflowTransferPOJO.getData().getData(), data);

            SupplierEntityExt supplierEntityExt = new SupplierEntityExt();
            supplierEntityExt.setId(dataId);
            supplierEntityExt.setCorpid(corpid);
            supplierEntityExt.setData(data);
            supplierEntityExt.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
            supplierEntityExt.setOwnerId(getOwnerId(data));
            supplierEntityExt.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));

            List<SupplierProductEntity> supplierProductEntities = JSON.parseArray(data.getString(StringConstant.PRODUCT), SupplierProductEntity.class);
            List<SupplierUserEntity> supplierUserEntities = JSON.parseArray(data.getString(StringConstant.USER_TEAM), SupplierUserEntity.class);

            FormDataUtil.removeSystemData(data);
            data.remove(StringConstant.PRODUCT);
            data.remove(StringConstant.USER_TEAM);
            if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE.getType())) {
                supplierEntityExt.setFlowStatus(FlowStatusEnum.PASS.getType());
            }
            supplierModel.update(supplierEntityExt);
            // 回退被删掉的子表单
            updateBackSubForm(supplierEntityExt, corpid, IndexTypeEnum.IDX_SAAS_SUPPLIER_SUB);
            //回退被删掉的富文本
            updateBackRichText(taskId, workflowTransferPOJO);
            // 团队处理
            saveUserTeam(supplierUserEntities, corpid, supplierEntityExt.getId());
            // 产品处理
//            saveProduct(supplierProductEntities, corpid, supplierEntityExt.getId());
        }
    }

    @Override
    public void approvalFailed(Long taskId, WorkflowTransferPOJO workflowTransferPOJO, Integer taskType) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Data workflowData = workflowTransferPOJO.getData();
            Long dataId = workflowData.getId();
            Long formId = workflowData.getFormId();
            Integer businessType = workflowData.getBusinessType();
            Integer saasMark = workflowData.getSaasMark();
            SupplierEntityExt supplierEntityExt = new SupplierEntityExt();
            supplierEntityExt.setId(dataId);
            if (Objects.equals(TaskTypeEnum.REVOKE.getType(), taskType)) {
                supplierEntityExt.setFlowStatus(FlowStatusEnum.REVOKE.getType());
            } else {
                supplierEntityExt.setFlowStatus(FlowStatusEnum.REJECT.getType());
            }
            supplierEntityExt.setCorpid(corpid);
            supplierEntityExt.setUpdateTime(DateTimeUtil.getInt());
            supplierModel.update(supplierEntityExt);
            // 子表单
            DelEnum del = DelEnum.APPROVE_FAILED;

            paasFormSubDataModel.deleteBatchByDataId(Collections.singletonList(dataId), corpid, IndexTypeEnum.IDX_SAAS_SUPPLIER_SUB, del);
            //富文本
            deleteFormRichText(dataId, corpid, formId, businessType, saasMark, DelEnum.NORMAL);

            List<SupplierUserEntity> userEntities = supplierUserModel.getSupplierUserListBySupplierId(corpid, dataId);
            if (CollectionUtils.isNotEmpty(userEntities)) {
                supplierUserModel.deleteBatchUser(userEntities, corpid, del.getDel());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowSupplierStrategy.approvalFailed error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    private void saveProduct(List<SupplierProductEntity> supplierProductEntities, String corpid, Long id) throws XbbException {
        try {
            List<Long> ids = new ArrayList<>();
            supplierProductEntities.forEach(v -> ids.add(v.getId()));

            List<SupplierProductEntity> productEntities = supplierProductModel.getSupplierProductBySupplierId(corpid, id);
            List<Long> delIds = productEntities.stream().filter(v -> !ids.contains(v.getId())).map(SupplierProductEntity::getId).collect(Collectors.toList());

            supplierProductModel.deleteByKeys(delIds, corpid);

            supplierProductModel.updateBatch(supplierProductEntities, corpid);

        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowSupplierStrategy.saveProduct error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    private void saveUserTeam(List<SupplierUserEntity> supplierUserEntities, String corpid, Long id) throws XbbException {
        try {

            List<Long> ids = new ArrayList<>();
            supplierUserEntities.forEach(v -> ids.add(v.getId()));

            List<SupplierUserEntity> userEntities = supplierUserModel.getSupplierUserListBySupplierId(corpid, id);
            List<SupplierUserEntity> userEntityList = userEntities.stream().filter(v -> !ids.contains(v.getId())).collect(Collectors.toList());

            supplierUserModel.deleteBatchUser(userEntityList, corpid, DelEnum.DELETE.getDel());

            supplierUserModel.updateBatch(supplierUserEntities, corpid);

        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowSupplierStrategy.saveUserTeam error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
